import { ref } from 'vue'
import { defineStore } from 'pinia'
import setting from '@/config/setting'
import localStore from '@/utils/storage'
import { ConfigProvider } from 'ant-design-vue'

const localTheme = localStore.get('theme') || {}
const themeAll = Object.assign({}, setting.theme, localTheme)

const setDefault = (them) => {
  ConfigProvider.config({
    theme: {
      primaryColor: them.color
    }
  })
  document.getElementsByTagName('body')[0].setAttribute('mask-style', them.maskStyle)
}

setDefault(themeAll)

export const useThemeStore = defineStore('theme', () => {
    const theme = ref(themeAll)

    const setItemValue = (value, item) => {
      if (!(item in setting.theme)) {
        return false
      }
      if (setting.theme[item] === value) {
        delete localTheme[item]
      } else {
        localTheme[item] = value
      }
      theme.value[item] = value
      if (item === 'maskStyle') {
        document.getElementsByTagName('body')[0].setAttribute('mask-style', value)
      }
      localStore.set('theme', localTheme)
    }

    const restoreDefaultTheme = () => {
      theme.value = Object.assign({}, setting.theme)
      setDefault(theme.value)
      localStore.remove('theme')
      return theme.value
    }

    return {
      theme,
      setItemValue,
      restoreDefaultTheme
    }
  }
)
